<script type="application/javascript">
  const checkCanSyncInterval = 1000; // ms
  // check if we are using IME, which will be interrupt by the sync
  let isTypingUsingIME = false;
  document.addEventListener('compositionstart', () => {
    isTypingUsingIME = true;
  });
  document.addEventListener('compositionend', () => {
    isTypingUsingIME = false;
  });
  // after we sync, set this to false
  let deSync = false;
  setInterval(async function checkCanSync() {
    // don't trigger sync if user is typing using IME
    if (isTypingUsingIME) return;
    // debounced sync indicator, will be true if there is no change in the disc for several seconds
    const canSync = (await fetch('/linonetwo/watch-fs-can-sync').then(response => response.text())) === 'true';
    if (!deSync && !canSync) {
      // we have previously synced, and server have changes that is not debounced yet
      deSync = true;
    }
    if (canSync && deSync) {
      $tw.syncer.syncFromServer();
      deSync = false;
    }
  }, checkCanSyncInterval);
</script>
